// pages/devices/devices.js
import request from "../../utils/request.js";
const themeManager = require("../../utils/theme.js");

Page(themeManager.enhancePage({
  data: {
    device: {},
    timeRange: "7d",
    latestData: {},
    currentTheme: 'dark', // 添加主题状态

    // 视图模式 ('chart' | 'table')
    viewMode: "chart",

    // 图表相关
    ec: {
      onInit: null,
    },
    chartData: [],
    varianceData: null,
    hasVarianceData: false,

    // 查询参数
    loading: false,

    // 参数选择
    parameterIndex: 0,
    parameterOptions: [
      { value: "temperature", label: "温度" },
      { value: "humidity", label: "湿度" },
      { value: "pm2_5", label: "PM2.5" },
      { value: "bacteria", label: "细菌" },
      { value: "fresh_air", label: "新鲜空气" },
      { value: "carb_momo", label: "一氧化碳" },
      { value: "methanal", label: "甲醛" },
      { value: "nitro_dio", label: "二氧化氮" },
      { value: "ozone", label: "臭氧" },
      { value: "radon", label: "氡" },
    ],

    selectedParameter: { value: "temperature", label: "温度" },

    // 数据类型选择
    dataTypeOptions: [
      { value: "min", label: "最小值", checked: false },
      { value: "max", label: "最大值", checked: false },
      { value: "avg", label: "平均值", checked: true },
      { value: "var", label: "方差", checked: false },
    ],

    selectedDataType: { value: "avg", label: "平均值" },

    // 表格数据
    deviceData: [],
    currentPage: 1,
    pageSize: 10,
    totalPages: 1,

    // 参数单位映射
    parameterUnits: {
      temperature: "°C",
      humidity: "%RH",
      pm2_5: "μg/m³",
      bacteria: "CFU",
      fresh_air: "%",
      carb_momo: "ppm",
      methanal: "mg/m³",
      nitro_dio: "μg/m³",
      ozone: "ppb",
      radon: "Bq/m³",
    },
  },

  onLoad: function (options) {
    // 获取从上一页传递的参数
    this.loadDeviceData(options.deviceId);
  },

  // 加载设备数据
  loadDeviceData: function (deviceId) {
    console.log("加载设备数据:", deviceId);
    request
      .get("/devices/my_devices/" + deviceId)
      .then((res) => {
        if (res?.data) {
          this.setData({
            device: res.data,
            loading: false,
          });

          this.loadChartData(res.data.uuid); // 加载图表数据
          console.log("设备数据加载成功:", res.data);
        }
      })
      .catch((err) => {
        console.error("数据加载失败:", err);
        this.setData({ loading: false });
        wx.showToast({ title: "数据加载失败", icon: "none" });
      });
  },

  getTimeRangeISO: function (range) {
    const now = new Date();
    let targetTime;

    switch (range) {
      case "24h":
        targetTime = new Date(now.getTime() - 24 * 60 * 60 * 1000); // 24小时前
        break;
      case "7d":
        targetTime = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000); // 7天前
        break;
      case "30d":
        targetTime = new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000); // 30天前
        break;
      default:
        targetTime = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000); // 默认7天前
    }

    // 转换为ISO格式字符串（包含时区信息）
    return targetTime.toISOString();
  },

  loadChartData: function (deviceId) {
    const parameter = this.data.selectedParameter.value; // 如 'temperature'
    const dataType = this.data.selectedDataType.value; // 如 'avg'

    if (!deviceId) {
      deviceId = this.data.device.uuid; // 如果没有传入deviceId，则使用当前设备的uuid
    }

    request
      .get(
        "/data/my_data?device_id=" +
          deviceId +
          "&after=" +
          this.getTimeRangeISO(this.data.timeRange)
      )
      .then((res) => {
        if (res?.data) {
          // 提取对应统计类型和参数的数据
          const processedData = res.data.items.map((item) => ({
            x: item.created_at, // 时间戳
            y: item[dataType][parameter], // 如 item.avg.temperature
          }));

          console.log("原始图表数据:", res.data.items);
          console.log("处理后的图表数据:", processedData);

          this.setData({
            chartData: processedData,
            loading: false,
          });

          this.initChart(); // 重新绘制图表
        }
      })
      .catch((err) => {
        console.error("数据加载失败:", err);
        this.setData({ loading: false });
        wx.showToast({ title: "数据加载失败", icon: "none" });
      });
  },

  // 初始化图表
  initChart: function () {
    console.log("初始化图表 - 开始");
    console.log("当前图表数据:", this.data.chartData);

    if (!this.data.chartData || this.data.chartData.length === 0) {
      wx.showToast({
        title: "设备暂无数据，无法查看图表",
        icon: "none",
      });
      return;
    }

    this.drawChart();
  },

  // 绘制图表
  drawChart: function () {
    const query = wx.createSelectorQuery();
    console.log("绘制图表 - 开始");
    query
      .select("#temperatureChart")
      .fields({
        node: true,
        size: true,
      })
      .exec((res) => {
        console.log("绘制图表 - 选择器查询结果:", res);
        if (res[0]) {
          const canvas = res[0].node;
          const ctx = canvas.getContext("2d");
          const dpr = wx.getSystemInfoSync().pixelRatio;

          canvas.width = res[0].width * dpr;
          canvas.height = res[0].height * dpr;
          ctx.scale(dpr, dpr);

          // 在这里绘制你的图表
          this.renderChart(ctx, res[0].width, res[0].height);
        }
      });
  },

  renderChart: function (ctx, width, height) {
    const chartData = this.data.chartData;

    console.log("绘制图表 - 数据:", chartData);

    // 你原来的绘制逻辑
    const padding = 30;
    const xScale = (width - 2 * padding) / (chartData.length - 1);
    const yValues = chartData.map((item) => item.y);
    const yMax = Math.max(...yValues);
    const yMin = Math.min(...yValues);
    const yRange = yMax - yMin;
    const yPadding = yRange * 0.05;
    const yScale = (height - 2 * padding) / (yMax + yPadding - yMin - yPadding);

    // 绘制标题
    ctx.font = "14px sans-serif";
    ctx.fillStyle = "#fff";
    ctx.textAlign = "center";
    ctx.fillText(
      `${this.data.selectedParameter.label}（${this.data.selectedDataType.label}）`,
      width / 2,
      15
    );

    // 绘制坐标轴
    ctx.beginPath();
    ctx.moveTo(padding, padding); // 原点
    ctx.lineTo(padding, height - padding); // y轴
    ctx.lineTo(width - padding, height - padding); // x轴
    ctx.strokeStyle = "#e5e7eb"; // 浅灰色坐标轴
    ctx.stroke();

    // 绘制x轴刻度和日期标签
    ctx.font = "10px sans-serif";
    ctx.fillStyle = "#9ca3af"; // 浅灰色文字
    ctx.textAlign = "center";

    chartData.forEach((item, index) => {
      const x = padding + index * xScale;
      const yAxisBottom = height - padding;

      // 刻度线
      ctx.beginPath();
      ctx.moveTo(x, yAxisBottom);
      ctx.lineTo(x, yAxisBottom + 3); // 底部刻度线
      ctx.stroke();

      // 日期标签（每2个点显示一次，避免重叠）
      if (index % 2 === 0) {
        const date = new Date(item.x);
        const dateStr = `${date.getMonth() + 1}/${date.getDate()}`; // 简化日期显示
        ctx.save();
        ctx.translate(x, yAxisBottom + 12);
        ctx.rotate(-Math.PI / 4); // 倾斜45度
        ctx.fillText(dateStr, 0, 0);
        ctx.restore();
      }
    });

    // 绘制y轴刻度和数值标签
    const ySteps = 5; // 5个主要刻度
    const yStepValue = (yMax + yPadding - yMin - yPadding) / ySteps;

    for (let i = 0; i <= ySteps; i++) {
      const value = yMin + yPadding + i * yStepValue;
      const y = height - padding - (i * (height - 2 * padding)) / ySteps;

      // 刻度线
      ctx.beginPath();
      ctx.moveTo(padding, y);
      ctx.lineTo(padding - 3, y); // 左侧刻度线
      ctx.stroke();

      // 数值标签
      ctx.save();
      ctx.textAlign = "right";
      ctx.fillText(value.toFixed(1), padding - 8, y + 4);
      ctx.restore();
    }

    // 绘制折线（先绘制完整的折线路径）
    ctx.beginPath();
    ctx.strokeStyle = "#3b82f6";
    ctx.lineWidth = 2;

    chartData.forEach((item, index) => {
      const x = padding + index * xScale;
      const y = height - padding - (item.y - yMin - yPadding) * yScale;

      if (index === 0) {
        ctx.moveTo(x, y);
      } else {
        ctx.lineTo(x, y);
      }
    });

    ctx.stroke(); // 绘制完整的折线

    // 然后绘制数据点（单独绘制，不影响折线）
    chartData.forEach((item, index) => {
      const x = padding + index * xScale;
      const y = height - padding - (item.y - yMin - yPadding) * yScale;

      // 每个数据点单独绘制
      ctx.beginPath();
      ctx.arc(x, y, 3, 0, 2 * Math.PI);
      ctx.fillStyle = "#3b82f6";
      ctx.fill();
    });

    return ctx;
  },

  // 切换时间范围
  changeTimeRange: function (e) {
    const range = e.currentTarget.dataset.range;
    this.setData({
      timeRange: range,
    });

    // 重新加载图表数据
    this.loadChartData();

    wx.showToast({
      title: `切换到${range}视图`,
      icon: "none",
      duration: 1000,
    });
  },

  // 数据类型选择
  onParameterChange: function (e) {
    const index = parseInt(e.detail.value);
    this.setData({
      parameterIndex: index,
      selectedParameter: this.data.parameterOptions[index],
    });
    this.loadChartData();
  },

  // 数据统计类型选择
  onDataTypeChange: function (e) {
    const index = parseInt(e.detail.value);
    this.setData({
      dataTypeIndex: index,
      selectedDataType: this.data.dataTypeOptions[index],
    });
    this.loadChartData();
  },

  updateNickname: function (e) {
    wx.showModal({
      title: "修改设备昵称",
      content: this.data.device.nickname,
      editable: true,
      placeholderText: "请输入设备昵称",
      success: (res) => {
        if (res.confirm && res.content) {
          const newNickname = res.content;
          if (!newNickname) {
            wx.showToast({
              title: "请输入有效的昵称",
              icon: "none",
            });
            return;
          }

          request
            .post(`/devices/${this.data.device.uuid}/set_nickname`, {
              nickname: newNickname,
            })
            .then((res) => {
              wx.showToast({
                title: "昵称更新成功",
                icon: "success",
              });
              this.setData({
                "device.nickname": newNickname,
              });
            })
            .catch((err) => {
              wx.showToast({
                title: "昵称更新失败",
                icon: "none",
              });
              console.error("更新设备昵称失败:", err);
            });
        }
      },
    });
    return;
  },

  // 解绑设备
  unbindDevice: function () {
    wx.showModal({
      title: "确认解绑",
      content: "确定要解绑此设备吗？解绑后将无法继续监控设备数据。",
      success: (res) => {
        if (res.confirm) {
          wx.showToast({
            title: "设备已解绑",
            icon: "success",
          });

          // 延迟返回上一页
          setTimeout(() => {
            wx.navigateBack();
          }, 1500);
        }
      },
    });
  }
}));
